package com.yoku.user;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * Desc:
 * Author: <a href="xiahj@terminus.io">xiahj</a>
 * Date: 2016/12/15
 */
public class test {

    //redis 分布式锁
    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i<5; i++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    print("abcdef");
                }
            });

            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    print("123456");
                }
            });
            thread.start();
            thread1.start();
        }

    }

    public static void print(String name){
        Config config = new Config();
        config.useSingleServer().setAddress("127.0.0.1:6379");
        RedissonClient redisson = Redisson.create(config);
        RLock rLock = redisson.getLock("myLock");
        rLock.lock(2, TimeUnit.SECONDS);

        for (int i=0; i<name.length(); i++){
            System.out.println(name.charAt(i));

            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        rLock.unlock();
    }

}
